package org.bluedream.core.utils.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import org.bluedream.comm.utils.EmptyUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阿里云短信平台 群发短信工具类
 * @ClassName SmsUtil
 * @Description TODO
 * @Author Administrator
 * @Data 2021/12/9 15:31
 * @Version
 */
public class SmsUtil {
    /*// regionId:系统指定Id，不得修改
    private static String regionId = "cn-hangzhou";
    //accessKey
    private static String accessKeyId = "LTAI4GGJJqW7Hz9SJNCKuvup";
    private static String accessSecret = "1uE5X9PDvhaRBVKdObXzwmP5EKQiwk";
    //短信服务的服务接入地址
    private static String domain= "dysmsapi.aliyuncs.com";
    //短信API产品名称（短信产品名固定，无需修改）
    private static String product = "Dysmsapi";
    //签名
    private static String signName = "城中城购物广场";
    //模板代码
    private static String templateCode = "SMS_230675173";*/

    public static Client createClient(String accessKeyId , String accessSecret , String domain) throws Exception{
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessSecret);
        config.endpoint = domain;
        return new Client(config);
    }

    private static String getJSONStr(int count , String msg){
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        for (int i = 0; i < count; i++) {
            sb.append(msg);
            if (i != count - 1){
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    private static String getJSONStr4List(List<String> msg){
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        for (int i = 0; i < msg.size(); i++) {
            sb.append(msg.get(i));
            if (i != msg.size() - 1){
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    /**
     * 发送短信
     * @param sms
     * @return
     */
    public static String sendSms(Sms sms) throws Exception{
        Client client = createClient(Sms.accessKeyId , Sms.accessSecret , Sms.domain);

        String sendMsg = "{\"code\":\"" + sms.getContent() + "\"}";
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(sms.getPhone());
        request.setSignName(sms.getSignName());
        request.setTemplateCode(sms.getTemplateCode());
        request.setTemplateParam(sendMsg);

        SendSmsResponse sendResp = client.sendSms(request);
        String errorCode = sendResp.body.code;
        String errorMsg = sendResp.body.message;

        if (!errorCode.equals("OK")){
            System.out.println("code:" + errorCode + "; message:" + errorMsg);
            return "code:" + errorCode + "; message:" + errorMsg;
        }
        //2.等待 10 秒钟后查询结果
        String bizId = sendResp.body.bizId;
        return getSendResult(sms.getPhoneList(), client, bizId);
    }

    /**
     * 群发短信
     * @param sms
     * @return
     */
    public static String sendBatchSms(Sms sms) throws Exception{
        Client client = createClient(Sms.accessKeyId , Sms.accessSecret , Sms.domain);
        //phoneNumber JSON字符串
        String phoneNumberJSON = getJSONStr4List(sms.getPhoneList());
        //签名        JSON字符串
        String signNameJSONStr = getJSONStr(sms.getPhoneList().size() , "\"" + sms.getSignName() + "\"");
//        ${name}： 兹定于${date}于${place}举行${content}活动，望周知！
        List<String> messages = new ArrayList<>();
        if (EmptyUtil.isNoEmpty(sms.getContent()) && EmptyUtil.isNoEmpty(sms.getNameList()) && EmptyUtil.isNoEmpty(sms.getDate()) && EmptyUtil.isNoEmpty(sms.getPlace())){
            for (int i = 0; i < sms.getNameList().size(); i++) {
                String msg = "{\"name\":\"" + sms.getNameList().get(i) + "\",\"date\":\"" + sms.getDate() + "\",\"place\":\"" + sms.getPlace() + "\",\"content\":\"" + sms.getContent() + "\"}";
                messages.add(msg);
            }
        }

        // 消息内容    JSON
        String templateParamJsonStr;
        if (EmptyUtil.isNoEmpty(messages)){
            templateParamJsonStr = getJSONStr4List(messages);
        }else {
            templateParamJsonStr = null;
        }


        SendBatchSmsRequest sendReq = sendBatchSmsRequest(phoneNumberJSON , signNameJSONStr , sms.getTemplateCode() , templateParamJsonStr);

        SendBatchSmsResponse sendResp = client.sendBatchSms(sendReq);
        String errorCode = sendResp.body.code;
        String errorMsg = sendResp.body.message;
        if (!errorCode.equals("OK")){
            System.out.println("code:" + errorCode + "; message:" + errorMsg);
            return "code:" + errorCode + "; message:" + errorMsg;
        }
        //2.等待 10 秒钟后查询结果
        String bizId = sendResp.body.bizId;
        return getSendResult(sms.getPhoneList(), client, bizId);
    }

    private static SendBatchSmsRequest sendBatchSmsRequest(String phoneNumberJSON , String signNameJSONStr , String templateCode , String templateParamJsonStr){
        SendBatchSmsRequest sendReq = new SendBatchSmsRequest();
        sendReq.setPhoneNumberJson(phoneNumberJSON);
        sendReq.setSignNameJson(signNameJSONStr);
        sendReq.setTemplateCode(templateCode);
        sendReq.setTemplateParamJson(templateParamJsonStr);
        return sendReq;
    }

    private static String getSendResult(List<String> phoneNumbers, Client client, String bizId) throws Exception {
        Common.sleep(10000);
        StringBuffer sendErrorPhonesStr = new StringBuffer();
        StringBuffer sendingPhoneStr = new StringBuffer();
        StringBuffer sendOKPhoneStr = new StringBuffer();
        //3.查询结果
        for (String phoneNum:phoneNumbers
        ) {
            QuerySendDetailsRequest queryReq = new QuerySendDetailsRequest();
            queryReq.setPhoneNumber(phoneNum);
            queryReq.setBizId(bizId);
            queryReq.setSendDate(com.aliyun.darabonbatime.Client.format("yyyyMMdd"));
            queryReq.setPageSize(10L);
            queryReq.setCurrentPage(1L);
            QuerySendDetailsResponse queryResp = client.querySendDetails(queryReq);
            List<QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO> dtos = queryResp.body.smsSendDetailDTOs.smsSendDetailDTO;
            for (QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO dto : dtos
                 ) {
                if (("" + dto.sendStatus + "").equals("3")){
                    sendOKPhoneStr.append(dto.phoneNum + "发送成功，接收时间：" + dto.receiveDate + "；");
                    System.out.println(dto.phoneNum + "发送成功，接收时间：" + dto.receiveDate);
                }else if (("" + dto.sendStatus + "").equals("2")){
                    sendErrorPhonesStr.append(dto.phoneNum + "：发送失败；"  + "；");
                    System.out.println(dto.phoneNum + "发送失败");
                }else {
                    sendingPhoneStr.append(dto.phoneNum + "：正在发送中；");
                    System.out.println(dto.phoneNum + "正在发送中");
                    /*List<String> tmpPhone = new ArrayList<>();
                    tmpPhone.add(dto.phoneNum);
                    getSendResult(tmpPhone , client , bizId);*/
                }
            }
        }
        String result = sendOKPhoneStr.toString() + sendErrorPhonesStr.toString() + sendingPhoneStr.toString();

        return result;
    }

    public static void main(String[] args)throws Exception {
        List<String> phones = new ArrayList<>();

        phones.add("15689120325");
        Sms sms = new Sms();
        sms.setPhoneList(phones);
        sms.setTemplateCode("SMS_230660202");
        sendBatchSms(sms);

/*        Map<String , String> sendUsers = new HashMap<>();
        sendUsers.put("15689120325" , "丁旭东");
        sendUsers.put("18660256615" , "测试");*/

        //1.发送短信
//        sendSms( phoneList, msg);
    }
}